package com.ckzp.jfinal.system.controller;

import com.ckzp.core.model.Datas;
import com.ckzp.core.util.StringUtil;
import com.ckzp.jfinal.base.PageSearch;
import com.ckzp.jfinal.interceptor.Admins;
import com.ckzp.jfinal.plugins.trans.TransData;
import com.ckzp.jfinal.plugins.tree.TreeNode;
import com.ckzp.jfinal.system.cache.SysMenuCache;
import com.ckzp.jfinal.system.cache.SysRoleCache;
import com.ckzp.jfinal.system.model.SysActivity;
import com.ckzp.jfinal.system.model.SysMenu;
import com.ckzp.jfinal.system.model.SysRole;
import com.ckzp.jfinal.system.util.SysMenuUtil;
import com.ckzp.jfinal.system.util.SysUserUtil;
import com.ckzp.jfinal.system.validate.SysRoleValidator;
import com.ckzp.plugins.layui.LayuiData;
import com.ckzp.core.json.JsonResult;
import com.ckzp.core.json.JsonUtil;
import com.ckzp.jfinal.base.BaseController;
import com.ckzp.jfinal.form.FormData;
import com.ckzp.jfinal.interceptor.Roles;
import com.ckzp.jfinal.system.model.SysUser;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 51594 on 2019/10/24.
 */
public class SysRoleController extends BaseController {

    /**
     * 用户列表
     */
    @Roles(roles = "system")
    public void RoleList() {
        render("RoleList.html");
    }

    /**
     * 添加用户接口
     */
    @Roles(roles = "system")
    public void AddSysRole() {
        FormData fd = FormData.dao().setActions("ADD");
        setAttr("role", new SysRole().put("index",1));
        setAttr("form", fd);
        render("ModifySysRole.html");
    }

    /**
     * 修改用户接口
     */
    @Roles(roles = "system")
    public void EditSysRole() {
        String role_id = getPara("role_id", "");
        SysRole sr = SysRole.dao.findById(role_id);

        FormData fd = FormData.dao().setActions("EDIT");
        setAttr("form", fd);
        setAttr("role", sr);
        render("ModifySysRole.html");
    }

    /**
     * 添加或修改用户信息API
     */
    @Roles(roles = "system")
    @Before(SysRoleValidator.class)
    public void ModifySysRoleApi() {
        Datas datas = getDatas();
        String role_id = datas.getStr("role_id");
        String actions = datas.getStr("actions");
        if ("EDIT".equals(actions)) {
            boolean results = SysRole.dao.findById(role_id)
                    .set("role_name", datas.getStr("role_name"))
                    .set("role_desc", datas.getStr("role_desc"))
                    .set("sindex", datas.getInt("sindex"))
                    .update();
            renderJson(JsonResult.n(results, "修改系统角色"));
        } else {
            boolean results = new SysRole()
                    .set("role_id", datas.getStr("role_id"))
                    .set("role_name", datas.getStr("role_name"))
                    .set("role_desc", datas.getStr("role_desc"))
                    .set("sindex", datas.getInt("sindex"))
                    .save();
            renderJson(JsonResult.n(results, "添加系统角色"));
        }
    }

    /**
     * 用户信息列表API
     */
    @Roles(roles = "system")
    public void SysRoleListApi() {
        //////////////////
        PageSearch ps = PageSearch.n().init(getRequest(), "sys_role").orderby("sindex");
        Page<SysRole> pages = ps.paginate(SysRole.dao);
        List datalist = pages.getList();
        renderJson(LayuiData.newData().setCount(pages.getTotalRow()).setData(datalist));
    }

    /**
     * 删除角色
     */
    public void DelSysRoleApi() {
        String role_id = getPara("role_id", "");
        int counts = Db.queryInt("select count(*) from sys_user_role where role_id=?", role_id);
        if (counts == 0) {
            if (SysRole.dao.findById(role_id).delete()) {
                renderJson(JsonResult.n(0, "删除成功"));
            } else {
                renderJson(JsonResult.n(9, "删除失败"));
            }
        } else {
            renderJson(JsonResult.n(9, "该角色下有" + counts + "用户,不能删除"));
        }
    }

    /**
     * 设置用户角色
     */
    @Roles(roles = "system")
    public void SetRoleUser() {
        String role_id = getPara("role_id");
        //
        List<SysUser> roleuserlist = SysUser.dao.
                find("select emp_id from sys_user_role where role_id=?", role_id);
        List roleuser_list = new ArrayList();
        for (int k = 0; k < roleuserlist.size(); k++) {
            SysUser role = roleuserlist.get(k);
            roleuser_list.add(role.getStr("emp_id"));
        }
        //取得系统所有人员
        List<SysUser> userlist = SysUserUtil.n().getActiveUserList();
        List user_list = new ArrayList();
        for (int k = 0; k < userlist.size(); k++) {
            SysUser user = userlist.get(k);
            TransData td = new TransData();
            td.setValue(user.getStr("emp_id"));
            String title = user.getStr("user_name") + "(" + user.getStr("dept_name") + "/" + user.getStr("emp_id") + "/" + user.getStr("login_id") + ")";
            td.setTitle(title);
            user_list.add(td);
        }
        //反回前端
        setForm(FormData.dao().setKey(role_id)
                .addData("roleuser_str", toJsonStr(roleuser_list))
                .addData("alluser_str", toJsonStr(user_list)));

        render("SetRoleUser.html");
    }


    /**
     * 设置用户角色
     */
    @Roles(roles = "system")
    public void SetRoleMenu() {
        String role_id = getPara("role_id");
        TreeNode node = TreeNode.newNode("tree").setTitle("菜单列表");
        FormData fd = SysMenuUtil.n().getMenuTreeData(role_id);
        //反回前端
        setForm(fd.setKey(role_id));
        render("SetRoleMenu.html");
    }


    /**
     * 设置用户角色api
     */
    @Roles(roles = "system")
    public void SetRoleUserApi() {
        String role_id = getPara("role_id", "");
        String json_userstr = getPara("user_str");
        if (role_id.length() > 0) {
            List list = JsonUtil.json2List(json_userstr, TransData.class);
            Db.update("delete from sys_user_role where role_id=?", role_id);
            for (int k = 0; k < list.size(); k++) {
                TransData td = (TransData) list.get(k);
                String emp_id = td.getValue();
                if (emp_id != null && emp_id.length() > 0) {
                    Db.save("sys_user_role", new Record().set("role_id", role_id).set("emp_id", emp_id));
                }
            }
        }
        Db.update("update sys_role set user_count=(select count(*) from sys_user_role where role_id=? ) where role_id=?", role_id, role_id);
        renderJson(JsonResult.n(0, "角色用户设置成功"));
    }

    /**
     * 设置用户角色api
     */
    @Roles(roles = "system")
    public void SetRoleMenuApi() {
        Datas datas = getDatas();
        String role_id = datas.getStr("roleid");
        String menuids = datas.getStr("menuids");
        List<SysMenu> menulist = SysMenu.dao.findAll();
        for (SysMenu menu : menulist) {
            int menuid = menu.mod.getInt("menu_id");
            String menu_role = "|" + menu.mod.getStr("menu_role") + "|";
            //如果原存在，现在已取消
            if (menu_role.indexOf("|" + role_id + "|") > -1 && menuids.indexOf("|" + menuid + "|") == -1) {
                menu_role = StringUtil.replace(menu_role, "|" + role_id + "|", "");
                menu_role = StringUtil.replace(menu_role, "||", "|");
                menu.set("menu_role", menu_role).set("menu_role_name", SysRoleCache.transRoleName(menu_role));
                menu.update();
            } else if (menu_role.indexOf("|" + role_id + "|") == -1 && menuids.indexOf("|" + menuid + "|") > -1) {
                if (menu_role.length() == 0) menu_role = "|";
                menu_role += role_id + "|";
                menu_role = StringUtil.replace(menu_role, "||", "|");
                menu.set("menu_role", menu_role).set("menu_role_name", SysRoleCache.transRoleName(menu_role));
                menu.update();
            }
        }
        SysMenuCache.reload();
        renderJson(JsonResult.n(0, "角色菜单设置成功"));
    }


    /**
     * 设置角色操作活动
     */
    @Admins(roles = "system", name = "设置角色操作活动页", log = false)
    public void SetRoleActivity() {
        String role_id = getPara("role_id");
        FormData fd = SysMenuUtil.n().getMenuAuthorTreeData(role_id);
        fd.addData("role_id", role_id);
        //反回前端
        setForm(fd.setKey(role_id));
        render("SetRoleActivity.html");
    }


    /**
     * 查询菜单活动Api
     */
    @Admins(roles = "system", name = "查询菜单活动Api", log = false)
    public void SysMenuActivityListDataApi() {
        int menu_id = getParaInt("menu_id", 0);
        String role_id = getParaStr("role_id", "");
        String sql = "from sys_activity a,sys_menu_activity ma where ma.act_id=a.act_id and ma.menu_id=?";
        PageSearch ps = PageSearch.n().setSql(sql).setSelect("select a.*").addValue(menu_id).init(getRequest());
        ps.orderby("a.sindex");
        Page<SysActivity> pages = ps.paginate(SysActivity.dao);
        List<SysActivity> datalist = pages.getList();
        for (SysActivity activity : datalist) {
            if (("|" + activity.mod.getStr("act_role", "") + "|").indexOf("|" + role_id + "|") > -1) {
                activity.put("has_role", 1);
            }
        }
        renderJson(LayuiData.newData().setData(datalist).setCount(pages.getTotalRow()));
    }

    /**
     * 查询菜单活动Api
     */
    @Admins(roles = "system", name = "查询菜单活动Api", log = false)
    public void ChangeActivityRoleApi() {
        String role_id = getPara("role_id");
        int act_id = getParaInt("act_id", 0);
        SysActivity activity = SysActivity.dao.findById(act_id);
        if (activity != null) {
            String act_role = activity.mod.getStr("act_role");
            if (!"|".equals(act_role.substring(0, 1))) act_role = "|" + act_role;
            if (!"|".equals(act_role.substring(act_role.length() - 1))) act_role = act_role + "|";
            if (act_role.indexOf("|" + role_id + "|") == -1) {
                act_role = act_role + role_id + "|";
                activity.set("act_role", act_role).set("act_role_name", SysRoleCache.transRoleName(act_role)).update();
            } else {
                act_role = StringUtil.replace(act_role, role_id + "|", "");
                activity.set("act_role", act_role).set("act_role_name", SysRoleCache.transRoleName(act_role)).update();
            }
            renderJson(JsonResult.n(9, "配置成功"));
        } else {
            renderJson(JsonResult.n(9, "活动不存在"));
        }
    }
}

